import {ObjectID} from "mongodb";
import {Promise} from 'es6-promise';
import PWSApp from "../../core/app";
import HomeBaseAction from "./act.base";
import {Magics} from "../../core/magics";
import {ModList} from "../../core/types";
import {Request, Response} from "express";
import * as utils from '../../core/utils';
import {RouteType} from "../../core/defines";
import {ErrCode} from "../../core/error.code";
import {MongoColls} from "../../config/mongo";
import CouponModel, {
    CouponInfo,
} from "../../models/mod.coupon";
import RedPacketModel, {
    RedPacketInfo
} from "../../models/mod.red.packet";

export default class CouponAction extends HomeBaseAction {

    name() {
        return `${this.app.name}CouponAction`;
    }

    private _couponMod: CouponModel;
    private _redPacketMod: RedPacketModel;

    constructor(app: PWSApp) {
        super(app);
        this._couponMod = new CouponModel(this.db.collection(MongoColls.COUPON));
        this._redPacketMod = new RedPacketModel(this.db.collection(MongoColls.RED_PACKET));
    }

    protected _setRoutes() {
        this._setRoot('/api/coupon'); //need login
        this._route(RouteType.POST, '/receive', this._actAddReceive);
        this._route(RouteType.GET, '/list', this._actGetCouponList);
    }

    private _actAddReceive(req: Request, res: Response) {
        let sess = req.session[Magics.SessUser] || {};
        let packet: RedPacketInfo;
        let userId: ObjectID;
        Promise.resolve().then(() => {
            let {id} = req.body;
            if (!utils.isObjectId(id)) {
                return Promise.reject({err_code: ErrCode.ArgsInvalid});
            }
            return this._redPacketMod.checkExist({_id: utils.toObjectId(id)});
        }).then((result: RedPacketInfo) => {
            packet = result;
            if (!packet) {
                return Promise.reject({err_code: ErrCode.RedPacketNotFound});
            }
            userId = utils.toObjectId(sess['_id']);
            let match = {
                user_id: userId,
                code: packet.code
            };
            return this._couponMod.checkExist(match);
        }).then((result: CouponInfo) => {
            if(result){
                return Promise.reject({err_code: ErrCode.RedPacketExisted});
            }
            let {code, name, type, stime, etime, limit, amount} = packet;
            let coupon: CouponInfo = {
                code, name, type, stime, etime, limit, amount,
                user_id: userId
            };
            return this._couponMod.receive(coupon);
        }).then(() => {
            res.send({err_code: ErrCode.Success});
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }

    private _actGetCouponList(req: Request, res: Response) {
        Promise.resolve().then(() => {
            let {page} = req.params;
            let sessUser = req.session[Magics.SessUser] || {};
            let curPage = utils.isPositiveNum(page) ? utils.toInt(page) : 0;

            let filter = {
                user_id: utils.toObjectId(sessUser['_id']),
                page: curPage,
                limit: 20
            };
            return this._couponMod.getCoupons(filter);
        }).then((data: ModList) => {
            let {limit, curr_page, total_count, records, total_page} = data;
            let result = {
                limit, curr_page, total_count, records, total_page,
                err_code: ErrCode.Success
            };
            res.send(result);
        }).catch((err) => {
            this._errHandler(req, res, err);
        });
    }

}